import React, { PureComponent, Fragment } from 'react';
import { Card, Form, Row, Input, Select, DatePicker, Button, Table, Divider, Popconfirm, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import lodash from 'lodash';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Ellipsis from '../../components/Ellipsis';
import UserManageAdd from './UserManageAdd';
import UserManageUpdate from './UserManageUpdate';
import UserBindSysName from './UserBindSysName';
import UserBindRole from './UserBindRole';
import { UserTypeArray, LockedArray, EnabledArray, UserTypeMapper, LockedMapper, EnabledMapper, SorterOrderMapper } from '../../utils/enum';
// import classNames from 'classnames';
import styles from './UserManage.less';

@connect(({ UserManageModel, GlobalEnumModel, loading }) => ({
  UserManageModel,
  GlobalEnumModel,
  queryLoading: loading.effects['UserManageModel/findByPage'],
  addUserLoading: loading.effects['UserManageModel/addUser'],
  getUserLoading: loading.effects['UserManageModel/getUser'],
  updateUserLoading: loading.effects['UserManageModel/updateUser'],
  userBindSysLoading: loading.effects['UserManageModel/userBindSys'],
}))
@Form.create()
export default class UserManage extends PureComponent {

  // 数据初始化
  componentDidMount() {
    this.findByPage();
  }

  // 查询数据
  findByPage = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    if (queryParam.expiredTimeStart) {
      queryParam.expiredTimeStart = moment(queryParam.expiredTimeStart).format('YYYY-MM-DD 00:00:00');
    }
    if (queryParam.expiredTimeEnd) {
      queryParam.expiredTimeEnd = moment(queryParam.expiredTimeEnd).format('YYYY-MM-DD 23:59:59');
    }
    dispatch({ type: 'UserManageModel/findByPage', payload: { ...queryParam, pageNo: 0 } });
    dispatch({ type: 'UserManageModel/save', payload: { selectedRowKeys: [] } });
  }

  // 表格数据过滤或跳页
  handleTableChange = (pagination, _, sorter) => {
    const { dispatch, UserManageModel } = this.props;
    const queryParam = { ...UserManageModel.queryParam, pageNo: pagination.current, pageSize: pagination.pageSize };
    // 排序
    if (sorter.field) {
      const sorterMapper = {};
      queryParam.orderField = sorterMapper[sorter.field];
      queryParam.sort = SorterOrderMapper[sorter.order];
    } else {
      queryParam.orderField = undefined;
      queryParam.sort = undefined;
    }
    dispatch({ type: 'UserManageModel/findByPage', payload: queryParam });
  }

  // 查询表单
  queryForm() {
    const { form: { getFieldDecorator }, queryLoading, UserManageModel: { queryParam } } = this.props;
    return (
      <Form onSubmit={this.findByPage} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="登录名">
            {getFieldDecorator('username', { initialValue: queryParam.username })(
              <Input placeholder="登录名" />
            )}
          </Form.Item>
          <Form.Item label="手机号">
            {getFieldDecorator('telephone', { initialValue: queryParam.telephone })(
              <Input placeholder="手机号" />
            )}
          </Form.Item>
          <Form.Item label="用户邮箱">
            {getFieldDecorator('email', { initialValue: queryParam.email })(
              <Input placeholder="用户邮箱" />
            )}
          </Form.Item>
          <Form.Item label="用户类型">
            {getFieldDecorator('userType', { initialValue: queryParam.userType })(
              <Select placeholder="用户类型" allowClear={true}>
                {UserTypeArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
        </Row>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="过期时间">
            {getFieldDecorator('expiredTimeStart', { initialValue: queryParam.expiredTimeStart ? moment(queryParam.expiredTimeStart) : undefined })(
              <DatePicker placeholder="过期时间-开始" style={{ width: 174 }} />
            )}
          </Form.Item>
          <Form.Item label="过期时间">
            {getFieldDecorator('expiredTimeEnd', { initialValue: queryParam.expiredTimeEnd ? moment(queryParam.expiredTimeEnd) : undefined })(
              <DatePicker placeholder="过期时间-结束" style={{ width: 174 }} />
            )}
          </Form.Item>
          <Form.Item label="帐号锁定">
            {getFieldDecorator('locked', { initialValue: queryParam.locked })(
              <Select placeholder="帐号锁定" allowClear={true}>
                {LockedArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="是否启用">
            {getFieldDecorator('enabled', { initialValue: queryParam.enabled })(
              <Select placeholder="是否启用" allowClear={true}>
                {EnabledArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  // 功能按钮
  actionButton() {
    const { dispatch, UserManageModel: { selectedRowKeys }, queryLoading } = this.props;
    const disabled = queryLoading || (selectedRowKeys && selectedRowKeys.length <= 0);
    return (
      <Fragment>
        <Button.Group style={{ marginBottom: 8 }}>
          <Button
            onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allSysName' });
              dispatch({ type: 'UserManageModel/save', payload: { showUserManageAdd: true } });
            }}
          >
            新增用户
          </Button>
          <Button
            disabled={disabled}
            onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allSysName' });
              dispatch({ type: 'UserManageModel/save', payload: { showUserBindSys: true } });
              this.userBindSysNameInit(selectedRowKeys);
            }}
          >
            分配系统
          </Button>
          <Button
            disabled={disabled}
            onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allRoleName' });
              dispatch({ type: 'UserManageModel/save', payload: { showUserBindRole: true } });
              this.userBindRoleInit(selectedRowKeys);
            }}
          >
            分配角色
          </Button>
        </Button.Group>
      </Fragment>
    );
  }

  // 数据表格
  getTable() {
    const { dispatch, UserManageModel, queryLoading } = this.props;
    const columns = [
      { title: '登录名', dataIndex: 'username', render: val => <a>{val}</a> },
      { title: '手机号', dataIndex: 'telephone' },
      { title: '邮箱', dataIndex: 'email' },
      {
        title: '用户类型', dataIndex: 'userType', render: val => {
          let userType = UserTypeMapper[val];
          if (!userType) userType = UserTypeMapper.error;
          return <span style={{ color: userType.color }}>{userType.label}</span>;
        },
      },
      { title: '过期时间', dataIndex: 'expiredTime' },
      {
        title: '是否锁定', dataIndex: 'locked', render: val => {
          let locked = LockedMapper[val];
          if (!locked) locked = LockedMapper.error;
          return <span style={{ color: locked.color }}>{locked.label}</span>;
        },
      },
      {
        title: '是否启用', dataIndex: 'enabled', render: val => {
          let enabled = EnabledMapper[val];
          if (!enabled) enabled = EnabledMapper.error;
          return <span style={{ color: enabled.color }}>{enabled.label}</span>;
        },
      },
      { title: '说明', dataIndex: 'description', render: val => <Ellipsis title={val} lines={1}>{val}</Ellipsis> },
      { title: '创建时间', dataIndex: 'createAt' },
      { title: '更新时间', dataIndex: 'updateAt' },
      {
        title: '操作', align: 'center', key: 'action',
        render: (_, record) => (
          <Fragment>
            <a
              onClick={() => {
                dispatch({ type: 'UserManageModel/save', payload: { showUserManageUpdate: true, updateUserName: record.username } });
                dispatch({ type: 'GlobalEnumModel/allSysName' });
                dispatch({ type: 'UserManageModel/getUser', payload: { username: record.username } });
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="left"
              title={`确定删除该帐号(${record.username})?`}
              okText="删除"
              cancelText="取消"
              onConfirm={() => this.delUser(record.username)}
            >
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];
    return (
      <Table
        size="middle"
        bordered={true}
        rowKey={record => record.id}
        rowSelection={{
          fixed: false,
          selectedRowKeys: UserManageModel.selectedRowKeys.map(item => item.id),
          onChange: (_, selectedRows) => {
            const max = 50;
            if (selectedRows.length > max) {
              message.warning(`最多只能选择${max}个用户，当前选择${selectedRows.length}个`);
              return;
            }
            const selectedRowKeys = selectedRows.map(item => ({ id: item.id, username: item.username }));
            dispatch({ type: 'UserManageModel/save', payload: { selectedRowKeys } });
          },
        }}
        columns={columns}
        loading={queryLoading}
        dataSource={UserManageModel.data}
        pagination={UserManageModel.pagination}
        onChange={this.handleTableChange}
      />
    );
  }

  // 删除选择的用户
  delSelectUser = (userId) => {
    const { dispatch, UserManageModel } = this.props;
    const selectedRowKeys = lodash.filter(UserManageModel.selectedRowKeys, user => userId !== user.id);
    dispatch({ type: 'UserManageModel/save', payload: { selectedRowKeys } });
  }

  // 新增用户
  addUser = (userData) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'UserManageModel/addUser',
      payload: { userData },
      successCallBack: user => {
        message.success(`新增用户成功 -> [${user.username}]`);
        this.addForm.resetFields();
      },
    });
  }

  // 删除用户
  delUser = (username) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'UserManageModel/delUser',
      payload: { username },
      successCallBack: user => {
        message.success(`删除用户成功 -> [${user.username}]`);
        this.addForm.resetFields();
      },
    });
  }

  // 更新用户
  updateUser = (userData) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'UserManageModel/updateUser',
      payload: { username: userData.username, userData },
      successCallBack: user => {
        message.success(`保存用户成功 -> [${user.username}]`);
        this.updateForm.resetFields();
      },
    });
  }

  // 批量重置绑定的系统
  userBindSys = (userList, selectSysNameList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'UserManageModel/userBindSys',
      payload: { usernameList: userList, sysNameList: selectSysNameList },
      successCallBack: result => {
        // console.log(result);
        message.success(`为用户分配系统成功 -> [${result.length}]个用户，[${result[0].sysNameList.length}]个系统`);
        this.userBindSysNameReset();
      },
    });
  }

  // 批量重置用户角色
  userBindRole = (userList, selectRoleList) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'UserManageModel/userBindRole',
      payload: { usernameList: userList, roleNameList: selectRoleList },
      successCallBack: result => {
        // console.log(result);
        message.success(`为用户分配角色成功 -> [${result.length}]个用户，[${result[0].roleList.length}]个角色`);
        this.userBindRoleReset();
      },
    });
  }

  render() {
    const { dispatch, addUserLoading, getUserLoading, updateUserLoading, userBindSysLoading, UserManageModel, GlobalEnumModel } = this.props;
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {this.actionButton()}
          {this.getTable()}
        </Card>
        <UserManageAdd
          userData={UserManageModel.addUserData}
          sysNameList={GlobalEnumModel.sysNameList}
          saveForm={form => { this.addForm = form }}
          visible={UserManageModel.showUserManageAdd}
          confirmLoading={addUserLoading}
          onCancel={() => {
            dispatch({ type: 'UserManageModel/save', payload: { showUserManageAdd: false } });
            this.addForm.resetFields();
          }}
          onOk={this.addUser}
        />
        <UserManageUpdate
          userData={UserManageModel.updateUserData}
          sysNameList={GlobalEnumModel.sysNameList}
          saveForm={form => { this.updateForm = form }}
          visible={UserManageModel.showUserManageUpdate}
          queryLoading={getUserLoading}
          confirmLoading={updateUserLoading}
          onCancel={() => {
            dispatch({ type: 'UserManageModel/save', payload: { showUserManageUpdate: false } });
            this.updateForm.resetFields();
          }}
          onOk={this.updateUser}
        />
        <UserBindSysName
          userList={UserManageModel.selectedRowKeys}
          sysNameList={GlobalEnumModel.sysNameList}
          resetStateFuc={resetState => { this.userBindSysNameReset = resetState }}
          initVisibleDataFuc={initVisibleData => { this.userBindSysNameInit = initVisibleData }}
          visible={UserManageModel.showUserBindSys}
          confirmLoading={userBindSysLoading}
          delSelectUser={this.delSelectUser}
          onCancel={() => {
            dispatch({ type: 'UserManageModel/save', payload: { showUserBindSys: false } });
            this.userBindSysNameReset();
          }}
          onOk={this.userBindSys}
        />
        <UserBindRole
          userList={UserManageModel.selectedRowKeys}
          roleNameList={GlobalEnumModel.roleNameList}
          resetStateFuc={resetState => { this.userBindRoleReset = resetState }}
          initVisibleDataFuc={initVisibleData => { this.userBindRoleInit = initVisibleData }}
          visible={UserManageModel.showUserBindRole}
          confirmLoading={false}
          delSelectUser={this.delSelectUser}
          onCancel={() => {
            dispatch({ type: 'UserManageModel/save', payload: { showUserBindRole: false } });
            this.userBindRoleReset();
          }}
          onOk={this.userBindRole}
        />
      </PageHeaderLayout>
    );
  }
}
